import type { Recordable, RouteRecordStringComponent, UserInfo } from '@croco/framework/types';

import { LOGIN_PATH } from '@croco/framework/constants';
import { resetAllStores, useUserStore } from '@croco/framework/stores';

import { service } from '#/api/request';
import { router } from '#/router';

/**
 * 获取用户信息
 */
export async function getUserDetails() {
    return service.get<UserInfo>(`/user/info`);
}

/**
 * 获取用户所有菜单
 */
export async function getUserMenus() {
    return service.get<RouteRecordStringComponent[]>(`/menu/all`);
}

/**
 * 获取用户权限码
 */
export async function getUserPermissions() {
    return service.get<Recordable<any>>(`/auth/codes`);
}

/**
 * 刷新accessToken
 */
export async function refreshToken() {
    const userStore = useUserStore();
    return service.post('/auth/refresh', {
        withCredentials: true,
        username: userStore.loginUser?.username,
    });
}

/**
 * 退出登录
 */
export async function logout() {
    const userStore = useUserStore();
    await service
        .post(`/auth/logout`, {
            withCredentials: true,
            username: userStore.loginUser?.username,
        })
        .then(async () => {
            await clearStores(false);
        });
}

/**
 * 清除缓存，并跳转回登录页
 * @param redirect 是否跳转回当前页面
 */
export async function clearStores(redirect: boolean = true) {
    const userStore = useUserStore();
    resetAllStores();
    userStore.setLoginExpired(false);
    // 回登录页带上当前路由地址
    await router.push({
        path: LOGIN_PATH,
        query: redirect ? { redirect: encodeURIComponent(router.currentRoute.value.fullPath) } : {},
    });
}
